package src.Fourteen;

import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class Shrewmouse extends JFrame {

    private ImageIcon imgMouse;
    private JLabel[] mouses;

    public Shrewmouse(){
        super();
        setResizable(false);
        getContentPane().setLayout(null);
        setTitle("简易打地鼠游戏");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ImageIcon img = new ImageIcon(getClass().getResource("2.jpg"));
        imgMouse = new ImageIcon((getClass().getResource("2.png")));
        mouses = new JLabel[6];
        for (int i = 0; i < 6; i++) {
            mouses[i] = new JLabel();
            mouses[i].setSize(imgMouse.getIconWidth(),imgMouse.getIconHeight());
            mouses[i].addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    Object source = e.getSource();
                    if(source instanceof JLabel){
                        JLabel mouse = (JLabel) source;
                        mouse.setIcon(null);
                    }
                }
            });
            getContentPane().add(mouses[i]);
        }
        mouses[0].setLocation(253,300);
        mouses[1].setLocation(333,250);
        mouses[2].setLocation(388,296);
        mouses[3].setLocation(362,364);
        mouses[4].setLocation(189,353);

        final JLabel backLabel = new JLabel();
        backLabel.setBounds(0,0,img.getIconWidth(),img.getIconHeight());
        setBounds(100,100,img.getIconWidth(),img.getIconHeight());
        backLabel.setIcon(img);
        getContentPane().add(backLabel);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    class Mthread implements Runnable{
        @Override
        public void run() {
            while (true){
                try {
                    Thread.sleep(1000);
                    int index = (int) (Math.random()*6);
                    if(mouses[index].getIcon() == null){
                        mouses[index].setIcon(imgMouse);
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public void ThreadRun(){
        Thread thread = new Thread(new Mthread());
        thread.start();
    }

    public static void main(String[] args) {
        Shrewmouse shrewmouse = new Shrewmouse();
        shrewmouse.ThreadRun();
    }

    
}
